﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using 数据库主从同步测试.Models;

namespace 数据库主从同步测试.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class NewsController : ControllerBase
    {

        public INewsService newsService;
        public NewsController(INewsService newService) {
            this.newsService = newService;
        }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<News>>>  Get() {
            return Ok(await newsService.GetNewsAsync());
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(int id) {
            var m = newsService.GetById(id);
            if (m == null) {
                return NotFound();
            }

            await newsService.DeleteByIdAsync(id);

            return NoContent();
        }

        [HttpGet("{id}")]
        [ProducesResponseType(200, Type = typeof(News))]
        [ProducesResponseType(404)]
        public IActionResult GetById(int id) {
            //if (!_repository.TryGetProduct(id, out var product)) {
            //    return NotFound();
            //}
            var m = newsService.GetById(id);
            if (m == null) {
                return NotFound();
            }

            return Ok(m);
        }



        [HttpPost]
        [ProducesResponseType(201, Type = typeof(CreateNews))]
        [ProducesResponseType(400)]
        public async Task<IActionResult> CreateAsync([FromBody] CreateNews news) {
            if (!ModelState.IsValid) {
                return BadRequest(ModelState);
            }

            var id = await  newsService.CreateAsync(news);
 
            return CreatedAtAction(nameof(GetById), new { id }, news);
        }
    }
}